#include "main.h"                  // Device header

void delay_us(uint32_t nus)
{
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;      
    ticks = nus * 168;                 

    told = SysTick->VAL;                    
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                tcnt += told - tnow;        
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks) 
            {
                break;                      
            }
        }
    }
}
//void delay_us(uint32_t xus)
//{
////	SysTick->LOAD = 168 * xus;				//设置定时器重装值
////	SysTick->VAL = 0x00;					//清空当前计数值
////	SysTick->CTRL = 0x00000005;				//设置时钟源为HCLK，启动定时器
////	while(!(SysTick->CTRL & 0x00010000));	//等待计数到0
////	SysTick->CTRL = 0x00000004;				//关闭定时器
//	
//	const volatile uint32_t start = SysTick->VAL;
//	volatile uint32_t cur;
//	while(1){
//		cur = SysTick->VAL; 
//		// 24bit donw
//		if(cur<start){
//			if((start-cur)>168*xus)
//				return;
//		}else{
//			if(((SysTick->LOAD)-cur+start)>168*xus)
//				return;
//		}
//	}
//	
//}

/**
  * @brief  毫秒级延时
  * @param  xms 延时时长，范围：0~4294967295
  * @retval 无
  */
void delay_ms(uint32_t xms)
{
	while(xms--)
	{
		delay_us(1000);
	}
}
 
/**
  * @brief  秒级延时
  * @param  xs 延时时长，范围：0~4294967295
  * @retval 无
  */
void delay_s(uint32_t xs)
{
	while(xs--)
	{
		delay_ms(1000);
	}
} 
